import store from '@/store'
import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'

router.beforeEach(async(to, from, next) => {
  // 加载进度条
  nProgress.start()
  // 判断vuex中的token是否存在
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
        // 在进入页面前，进行验证路由
        const menus = store.state.user.userInfo.roles.menus
        const routes = await store.dispatch('permission/filterRouter', menus)
        // 设置路由权限
        // 这里是筛选之后, 调用 router.addRoutes(筛选结果)可以将有权限的路由重新补回配置当

        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
        return
      }
      next()
    }
  } else {
    const whiteList = ['/login', '/404', '/test']
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  nProgress.done() // 完成进度条
})
